package com.haiwee.springbootjdbctemplate.dao.impl;

import com.haiwee.springbootjdbctemplate.dao.UserDao;
import com.haiwee.springbootjdbctemplate.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Auther: lichufeng
 * @Date: 2018/12/16 18:28
 * @Description:
 */
@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private  JdbcTemplate jdbcTemplate;



	@Override
	public List<User> queryUsers() {
		String sql = "select * from t_user";
		return jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper<>(User.class));
	}

	@Override
	public User getUser(Long id) {

		String sql = "select * from t_user where id = ?";

		User user = null;
		try {
			user = jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper<>(User.class));
		} catch (EmptyResultDataAccessException e) {

			return null;
		}
		return user;
	}

	@Override
	public int addUser(User user) {
		String sql = "insert into t_user(username, password) values(?, ?)";
		return jdbcTemplate.update(sql,user.getUsername(),user.getPassword());
	}

	@Override
	public int delUser(Long id) {
		String sql = "delete from t_user where id = ?";
		return jdbcTemplate.update(sql,id);
	}

	@Override
	public int editUser(User user,Long id) {
		String sql = "UPDATE t_user SET username = ? ,password = ? WHERE id = ?";
		return jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),id);
	}
}
